﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using SimpleTaskManager.Domain.SampleData;
using SimpleTaskManager.WebUI.Infrastructure;
using Ninject.Modules;
using SimpleTaskManager.Domain.Abstract;
using SimpleTaskManager.Domain.Concrete;
using Ninject;
using System.Web.Security;

namespace SimpleTaskManager.WebUI
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    /// <summary>
    /// class needed for interface injection to membership and role providers
    /// </summary>
    internal class MyNinjectModules : NinjectModule
    {
        public override void Load()
        {
            Bind<IUserRepository>().To<EFUserRepository>();
            Bind<IPasswordEncrypter>().To<SHA1PasswordEncrypter>();
        }
    }

    /// <summary>
    /// The main class of the web application
    /// </summary>
    public class MvcApplication : System.Web.HttpApplication
    {
        private IKernel _kernel = new StandardKernel(new MyNinjectModules());

        /// <summary>
        /// Registers global filters
        /// </summary>
        /// <param name="filters">The collection of global filters</param>
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        /// <summary>
        /// Registers the routes for the application
        /// </summary>
        /// <param name="routes">The collection of the routes</param>
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }
 
        /// <summary>
        /// The application entry point
        /// </summary>
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            _kernel.Inject(Membership.Provider);
            _kernel.Inject(Roles.Provider);

            ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());

            var context = new Domain.Concrete.EFDbContext();
            if (Initializer.IsFirstRun(context))
            {
                Initializer.InitializeData(context);
            }
        }
    }
}